package com.liuwei.netty.heartbeat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyHeartBeatServerHandler extends SimpleChannelInboundHandler<String>{

    // 读超时的超时次数
    int readIdleTimes = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        readIdleTimes = 0;
        log.info("服务端端收到的数据:" + msg);
        ctx.writeAndFlush("服务端已经收到心跳");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent) evt;
        switch (event.state()) {
            case READER_IDLE:
                readIdleTimes++;
                log.info("读超时");
                break;
            case WRITER_IDLE:
                log.info("写超时");
                break;
            case ALL_IDLE:
                log.info("读写超时");
                break;
        }
        // 如果超时次数大于3就关闭和客户端的连接
        if (readIdleTimes > 3) {
            log.info("读写超时3次,关闭连接");
            ctx.writeAndFlush("超时关闭");
            ctx.channel().close();
        }

    }
}
